using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using Microsoft.WowAddonStudio.FrameXml.Components.Support;
using Microsoft.WowAddonStudio.FrameXml.Serialization;
using Microsoft.WowAddonStudio.FrameXml.Serialization.LayoutFrames;
using Microsoft.WowAddonStudio.FrameXml.Services;
using Color=Microsoft.WowAddonStudio.FrameXml.Serialization.Color;

namespace Microsoft.WowAddonStudio.FrameXml.Components.Editors
{
    public class FontTreePickerEditorForm : TreePickerEditorForm
    {
        public FontTreePickerEditorForm(PickerElement tree, IServiceProvider provider)
            : base(tree, provider)
        {
        }

        protected override void ShowPreview()
        {
            base.ShowPreview();

            try
            {
                if (!string.IsNullOrEmpty(RelativePath) && FontService.FontExists(this.RelativePath))
                {
                    Bitmap bmp = new Bitmap(previewPictureBox.Width, previewPictureBox.Height);
                    Graphics drawingSurface = Graphics.FromImage(bmp);

                    var frameXmlGraphics = new FrameXmlGraphics((FrameXmlImageService)provider.GetService(typeof(FrameXmlImageService)), 
                                                                (FrameXmlFontService)provider.GetService(typeof(FrameXmlFontService)),
                                                                drawingSurface);

                    var fontString = new FontString
                                         {
                                             Text = Path.GetFileNameWithoutExtension(Path.GetFileName(this.RelativePath)),
                                             FontHeight = new FontHeight {AbsValue = new AbsValue {Value = 28}},
                                             Font = this.RelativePath,
                                             Color = Color.FromColor(System.Drawing.Color.Maroon),
                                             Shadow = new Shadow
                                                          {
                                                              Color = Color.FromColor(System.Drawing.Color.Black),
                                                              Offset = new Dimension { AbsDimension = new AbsDimension { X = 1, Y = -1 } }
                                                          }
                                         };


                    frameXmlGraphics.DrawFontString(fontString, previewPictureBox.ClientRectangle);

                    previewPictureBox.Image = bmp;
                }
            }
            catch (Exception e)
            {
                Trace.Write(e);
                previewPictureBox.Image = null;
            }
        }

        private FrameXmlFontService FontService
        {
            get { return (FrameXmlFontService)provider.GetService(typeof(FrameXmlFontService)); }
        }

    }
}